import { useState } from 'react'

const useNumInput = (
  defaultValue: number,
  config: {
    min?: number
    max?: number
    int?: boolean
  } = {}
) => {
  const { min = 0, max = 100, int = false } = config
  if (max < min) {
    throw new Error('max should be less than min')
  }
  const [value, setValue] = useState(defaultValue)
  const [strValue, setStringValue] = useState(defaultValue.toString())

  const onChange = (newStrValue: string) => {
    let newValue = +newStrValue
    if (isNaN(newValue)) {
      setStringValue(newStrValue)
      return
    }
    if (int) {
      newValue = Math.floor(newValue)
    }
    if (newValue < min || newValue > max) {
      setStringValue(newStrValue)
      return
    }
    setStringValue(newStrValue)
    setValue(newValue)
  }
  const onBlur = () => {
    let newValue = +strValue
    if (isNaN(newValue)) {
      setStringValue(defaultValue.toString())
      setValue(defaultValue)
      return
    }
    if (int) {
      newValue = Math.floor(newValue)
    }
    if (newValue < min) {
      setStringValue(`${min}`)
      setValue(min)
      return
    } else if (newValue > max) {
      setStringValue(`${max}`)
      setValue(max)
      return
    }
    setStringValue(`${newValue}`)
    setValue(newValue)
  }
  return [value, onChange, strValue, onBlur] as const
}

export default useNumInput
